import React from 'react'
import {fetchPost} from './common/request'
import { Tree,Table, Card, Button, Form, Message, Row, Col, DatePicker,Modal,Input,Lable, Select,Popconfirm } from 'antd'
const TreeNode = Tree.TreeNode
const FormItem = Form.Item
import {successNotify,errorNotify} from './common/common'
import {treeDeal} from './common/common.js'

class MessageTemplate extends React.Component {
  constructor (props) {
    super(props)
  }

  record = null;

  state = {
    appList: [],
    msgEnums: [],
    smsTypes: [],
    templateData : [],
    // 当前点击的appId
    selectedKey :null,
    servicerList :[],
    bizFuncList : [],
    record : {},
    sortedInfo: null,
    recordIsNew: false,
    newModalVis: false,
  }

  newTemplate() {
    fetchPost('/template/newTemp',this.state.record).then( json => {
      if (json.code != 200) {
        errorNotify('Add failure',json.msg)
      } else {
        successNotify('Add success')
        this.state.record = {}
        if (this.state.selectedKey)
        {
          this.getTemplateList(this.state.selectedKey[0])
        }
      }
    });
  }



  // 新增业务所填字段
  recordAppNameChange= (value, option)=> {
    this.props.form.resetFields()
    this.state.record.bizCode = null
    this.state.record.appId = value
    this.state.record.appName = option.props.children;
    this.state.record.sign = '【' + option.props.children+'】'

    this.getBizFuncList(value)
    // this.state.record.appId = value;
  }
  recordServicerChange = (value, option) => {
    this.state.record.servicerCode = value;
  }
  recordMsgTypeChange= (value, option)=> {
    this.state.record.msgType = value;
  }
  recordTempTypeChange= (value, option)=> {
    this.state.record.templateType = value;
  }
  recordContentChange= (e)=> {
    // this.state.record.servicerCode = e.target.value;
    this.state.record.content = e.target.value;
  }
  recordDescInfoChange= (e)=> {
    this.state.record.descInfo = e.target.value;
  }
  recordSignChange= (e)=> {
    this.state.record.sign = e.target.value;
  }
  recordBizChange= (value)=> {
    this.state.record.bizCode = value;
  }
  recordTypeChange = (value) => {
    this.state.record.type = value
  }


  // 加载树形控件
  onLoadTreeData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
    });
  }
  renderTreeNodes = (data) => {
    return data.map((item) => {
      return <TreeNode title={item.appName} isLeaf={item.isLeaf} key={item.appId}   dataRef={item} />;
    });
  }
  // 显示对应app信息
  loadTemplateInfo = (selectedKeys) => {
    if (selectedKeys) {
      this.state.selectedKey = selectedKeys
      this.getTemplateList(selectedKeys[0])
    } else {
      this.getTemplateList(this.state.selectedKey )
    }
  }


  // 新增和修改对话框的维护
  showNewModal = () => {
    this.getAppList()
    this.getMsgEnum()
    this.getSmsEnum()
    this.getServicerList()
    // this.state.
    this.props.form.resetFields()
    if (this.state.selectedKey){
      this.state.record.appId = this.state.selectedKey[0]
      for(var i=0,len=this.state.appList.length; i< len; i++){
        if(this.state.appList[i].appId === parseInt(this.state.record.appId) ){
          this.state.record.appName = this.state.appList[i].appName;
          this.state.record.sign = '【' + this.state.appList[i].appName +'】'
        }
      }
      this.getBizFuncList(this.state.record.appId)
    }

    this.setState({
      newModalVis: true,
      recordIsNew: true,
    });
  }
  // 新增和修改对话框的维护
  showUpdateModal = (record) => {
    this.props.form.resetFields();
    this.state.record = record
    this.setState({
      record : record,
      newModalVis: true,
      recordIsNew: false,
    });
  }

  handleVisOk = (e) => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // 判断是新增还是修改
        if(this.state.recordIsNew){
          this.newTemplate()
        }
        this.setState({
          newModalVis: false,
        });
      }
    });
  }
  handleVisCancel = (e) => {
    this.setState({
      newModalVis: false,
    });
  }


  componentDidMount() {
    this.getMsgEnum()
    this.getTemplateList()
    this.getAppList()

  }

  getTemplateList = (appId) => {

    var param = null;
    if(appId) {
      param = {}
      param.appId = appId
    }
    fetchPost('/template/getTemplateList',param).then( json => {

      // var temp = this.dealTemplateList(json.data)

      if (json.data != null) {
        this.setState({
          templateData: json.data
        });
      }
    });
  }

  getServicerList = () => {
    fetchPost('/servicer/getAllServicer').then( json => {
      if (json.data != null) {
        this.setState({
          servicerList : json.data
        });
      }
    });
  }

  getAppList() {
    fetchPost('/appInfo/getAppInfo').then( json => {
      if (json.data != null) {
        treeDeal(json.data)
        this.setState({
          appList: json.data
        });
      }
    });
  }


  //获取业务列表
  getBizFuncList(appId) {
    var param = null;
    if(appId) {
      param = {}
      param.appId = appId
    }
    fetchPost('/bizFunc/getBizFuncList',param).then( json => {
      if (json.data != null) {
        this.setState({
          bizFuncList: json.data
        });
      }
    });
  }

  getMsgEnum() {
    fetchPost('/template/getMsgType').then( json => {
      if (json.data != null) {
        this.setState({
          msgEnums: json.data
        });
      }
    });
  }

  getSmsEnum() {
    fetchPost('/template/getSmsType').then( json => {
      if (json.data != null) {
        this.setState({
          smsTypes : json.data
        });
      }
    });
  }

  dealTemplateList(templateData) {
    for (var i=0; i < templateData.length; i++) {
      if(templateData[i].templateType === 0){
        templateData[i].templateType = "No"
      } else {
        templateData[i].templateType = "Yes"
      }
    }
    return templateData
  }


  handleChange = (pagination, filters, sorter) => {
    this.setState({
      filteredInfo: filters,
      sortedInfo: sorter,
    });
  }

  // 删除选中
  onDeleteLists = () => {
  }

  render() {
    let { sortedInfo, filteredInfo } = this.state;
    sortedInfo = sortedInfo || {};
    filteredInfo = filteredInfo || {};

    const columns = [

      {
        title: 'Sign',
        dataIndex: 'sign',
        key: 'sign',
        width : 100,
        sorter: (a, b) => a.sign > b.sign ? 1 : -1,
        sortOrder: sortedInfo.columnKey === 'sign' && sortedInfo.order,
      },
      {
        title: 'Message type',
        dataIndex: 'msgType',
        key: 'msgType',
        width:90,
        sorter: (a, b) => a.msgType > b.msgType ? 1 : -1,
        sortOrder: sortedInfo.columnKey === 'msgType' && sortedInfo.order,
      }, {
        title: 'SMS type',
        dataIndex: 'type',
        key: 'type',
        width:90,
        sorter: (a, b) => a.type > b.type ? 1 : -1,
        sortOrder: sortedInfo.columnKey === 'type' && sortedInfo.order,
      }, /*{
        title: '来源',
        dataIndex: 'templateType',
        key: 'templateType',
        width: 40
      }, */{
        title: 'Template content',
        dataIndex: 'content',
        key: 'content',
        sorter: (a, b) => a.context > b.context ? 1 : -1,
        // width : 200,
        sortOrder: sortedInfo.columnKey === 'content' && sortedInfo.order,
      }, {
        title: 'Description',
        dataIndex: 'descInfo',
        key: 'descInfo',
        sorter: (a, b) => a.descInfo > b.descInfo ? 1 : -1,
        sortOrder: sortedInfo.columnKey === 'descInfo' && sortedInfo.order,
      }
      /*, {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
          width:200,
        render: (text, record) => {
          const {editable} = record;
          return (
            <div>
              <Button onClick={this.showUpdateModal.bind(this,record)}>
                修改
              </Button>
              <Popconfirm title="确定删除该条数据?" onConfirm={() => this.onDelete(record.key)}>
                <Button>
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        }
      }*/
    ];

    const appOptions = this.state.appList.map(d => <Option key={d.appId}>{d.appName}</Option>);
    const MsgTypeOptions = this.state.msgEnums? this.state.msgEnums.map(d => <Option key={d.code}>{d.message}</Option>) : null;
    const SmsTypeOptions = this.state.smsTypes? this.state.smsTypes.map(d => <Option key={d.code}>{d.desc}</Option>) : null;
    const servicerOptions = this.state.servicerList? this.state.servicerList.map(d => <Option key={d.servicerCode}>{d.servicerName}</Option>) : null;
    const bizFuncOptions = this.state.bizFuncList.map(d => <Option value={d.bizCode}>{d.bizName}</Option>);
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const { getFieldDecorator } = this.props.form;
    const { TextArea } = Input;
    return(
      <Card>
        <Row>
          <Col span={4}>
            <Tree ref="tree" loadData={this.onLoadTreeData} onSelect={this.loadTemplateInfo}>
              {this.renderTreeNodes(this.state.appList)}
            </Tree>
          </Col>

          <Col span={20}>
            <div>
              <Button style={{'margin-bottom':'10'}} onClick={this.showNewModal}>New configuration</Button>
              <Popconfirm title="Make sure to delete these data?" onConfirm={() => this.onDeleteLists()}>
                <Button  style={{display:'none'}}>
                  删除选中
                </Button>
              </Popconfirm>
            </div>
            <Table dataSource={this.state.templateData} onChange={this.handleChange} columns={columns}
                   pagination={{pageSize:10}} rowKey="msgTmpId"
                   >
            </Table>
          </Col>

        </Row>

        <Modal
          title={this.state.recordIsNew ? "New":"Modify"}
          visible={this.state.newModalVis}
          onOk={this.handleVisOk}
          onCancel={this.handleVisCancel}
        >
          <Form>
            <FormItem {...formItemLayout} label = "App name">

              {getFieldDecorator('appId', {
                initialValue : this.state.record? this.state.record.appId || "" : "",

                rules: [
                  { required: true, message: 'Please enter the app name!' },
                ],
              })(
                <Select placeholder="Please" onSelect={this.recordAppNameChange}>
                  {appOptions}
                </Select>
              )}
            </FormItem>


            <FormItem {...formItemLayout} label = "Biz type">

              {getFieldDecorator('bizCode', {
                initialValue : this.state.record? this.state.record.bizCode || "" : "",
                rules: [
                  { required: true, message: 'Please select a business type!' },
                ],
              })(
                <Select placeholder="Please select a business type!" onSelect={this.recordBizChange}>
                  {bizFuncOptions}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "Service provider">

              {getFieldDecorator('servicerCode', {
                initialValue : this.state.record? this.state.record.servicerCode || "" : "",

                rules: [
                  { required: true, message: 'Please enter the service provider!' },
                ],
              })(
                <Select placeholder="Please" onSelect={this.recordServicerChange}>
                  {servicerOptions}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "SMS send type">

              {getFieldDecorator('msgType', {
                initialValue : this.state.record? this.state.record.msgType || "" : "",

                rules: [
                  { required: true, message: 'Please select the sms send type!' },
                ],
              })(
                <Select placeholder="Please select the sms send type" onSelect={this.recordMsgTypeChange}>
                  {MsgTypeOptions}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "SMS send type">

              {getFieldDecorator('type', {
                initialValue : this.state.record? this.state.record.type || "" : "",
                rules: [
                  { required: true, message: 'Please select sms send type!' },
                ],
              })(
                <Select placeholder="Please select sms send type" onSelect={this.recordTypeChange}>
                  {SmsTypeOptions}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "Template type">

              {getFieldDecorator('templateType', {
                initialValue : this.state.record? this.state.record.templateType || "" : "",
                rules: [
                  { required: true, message: 'Please select the template type!' },
                ],
              })(
                <Select placeholder="Please select the template type!" onSelect={this.recordTempTypeChange}>
                  <Option value="1">Local template</Option>
                  <Option value="2">Third-party template</Option>
                </Select>
              )}
            </FormItem>


            <FormItem {...formItemLayout} label = "Content">

              {getFieldDecorator('content', {
                initialValue : this.state.record? this.state.record.content || "" : "",
                rules: [
                  { required: true, message: 'Please enter the content!' },
                ],
              })(
                <TextArea type="text" placeholder="The third-party template inputs the id, the normal template enters the template content, and the alternative word is represented by ##CODE##  " onChange={this.recordContentChange}/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "Description">

              {getFieldDecorator('descInfo', {
                initialValue : this.state.record? this.state.record.descInfo || "" : "",
                rules: [],
              })(
                <TextArea placeholder="Description" onChange={this.recordDescInfoChange}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label = "Sign">
              {getFieldDecorator('sign', {
                initialValue : this.state.record? this.state.record.sign || "" : "",
                rules: [
                  { required: true, message: 'Please enter the sign!' },
                ],
              })(
                <Input placeholder="Sign" onChange={this.recordSignChange}/>
              )}
            </FormItem>
          </Form>
        </Modal>
      </Card>
    );
  }
}


MessageTemplate = Form.create()(MessageTemplate)
export default MessageTemplate


